﻿using DotXxlJob.Core;
using DotXxlJob.Core.Config;
using XxlJobDotNetCore.Handler;
using XxlJobDotNetCore.Middleware;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using System.Reflection;

namespace XxlJobDotNetCore.Extension
{

    public static class DependencyInjectionExtersion
    {
        public static IServiceCollection AddxxlJobs(this IServiceCollection services, IConfiguration configurationSection)
        {
            services.AddXxlJobExecutor(configurationSection);
            var types = GetSubClassType(typeof(AbstractJobHandler));
            var methods = typeof(ServiceCollectionServiceExtensions).GetMethods();
            MethodInfo method = methods.FirstOrDefault(m => m.Name == "AddSingleton" && m.IsGenericMethod && m.GetGenericArguments().Length == 2);
            // 自动注册Job,请勿手动注册
            foreach (var type in types)
            {
                var registerMethod = method.MakeGenericMethod(new Type[] { typeof(IJobHandler), type });
                registerMethod.Invoke(services, new object[] { services });
            }
            services.AddAutoRegistry();
            return services;
        }
        public static List<Type> GetSubClassType(Type baseType)
        {
            //自动注册该类所在的namespace下的所有类
            var allTypes = typeof(TestTaskNetTestHandler).Assembly.GetTypes();
            return allTypes.Where(t => t.BaseType != null && t.BaseType.Equals(baseType)).ToList();
        }

        /// <summary>
        /// XXLJob执行器中间件
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseXxlJobExecutor(this IApplicationBuilder app)
        {
            return app.UseMiddleware<XxlJobExecutorMiddleware>();
        }
    }
}